package com.xinshujia.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.xinshujia.dto.DeviceDescDTO;
import com.xinshujia.entity.DeviceEntity;
import com.xinshujia.response.RespResult;
import com.xinshujia.service.DeviceService;
import com.xinshujia.utils.GsonUtil;
import org.springframework.web.bind.annotation.*;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-19 17:38       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 * 设备控制器
 */
@RestController
@RequestMapping("device")
public class DeviceController {
    private final DeviceService deviceService;

    public DeviceController(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    /**
     * 分页查询
     */
    @GetMapping("getDevicesByPage")
    public RespResult getDevicesByPage(@RequestParam("pageSize") Long pageSize,
                                       @RequestParam("pageNum") Long pageNum,
                                       @RequestParam("companyName") String companyName) {
        Page<DeviceEntity> pages = deviceService.findAllByPage(pageNum, pageSize, companyName);
        Gson gson = GsonUtil.googleGson();
        return RespResult.OK(gson.toJson(pages));
    }

    /**
     * 添加设备
     * @param: deviceEntity
     */
    @PostMapping("insert")
    public RespResult insertDevice(@RequestBody DeviceEntity deviceEntity){
        // 根据设备GUID查询设备
        DeviceEntity entity = deviceService.findDeviceByDeviceGuid(deviceEntity.getDeviceGuid());
        if(!ObjectUtils.isEmpty(entity)){
            return RespResult.Fail("设备GUID已存在");
        }

        boolean flag = deviceService.insertDevice(deviceEntity);
        if(flag){
            return RespResult.OK();
        }else{
            return RespResult.Fail();
        }
    }


    /**
     * 根据Id更新设备
     */
    @PutMapping("update")
    public RespResult updateDeviceById(@RequestBody DeviceEntity deviceEntity){
        boolean flag = deviceService.updateDeviceById(deviceEntity);
        if(flag){
            return RespResult.OK();
        }else{
            return RespResult.Fail();
        }
    }

    /**
     * 根据DeviceId查询设备详情
     */
    @GetMapping("getDeviceDescByDeviceGuid")
    public RespResult getDeviceDescByDeviceGuid(@RequestParam("deviceGuid") String deviceGuid){
        DeviceDescDTO deviceDescDTO = deviceService.getDeviceDescByDeviceGuid(deviceGuid);
        if(!ObjectUtils.isEmpty(deviceDescDTO)){
            Gson gson = GsonUtil.googleGson();
            return RespResult.OK(gson.toJson(deviceDescDTO));
        }else{
            return RespResult.Fail();
        }
    }
}
